/**
* 增加行，选中行才可以进行操作
*/
function addRow(){
	for (var i in selectedrows) {
		var selrow = selectedrows[i];
	}
	currentSheet.defaultrows = currentSheet.defaultrows + 1;
	reloadWorkBook();
	//selectedrows = {};
}
/**
* 增加列，选中列才可以进行操作
*/
function addCol(){
	for (var i in selectedcols) {
		var selcol = selectedcols[i];
	}
	currentSheet.defaultcols = currentSheet.defaultcols + 1;
	reloadWorkBook();
	//selectedcols = {};
}
/**
* 移除行，选中行才可以进行操作
*/
function removeRow(){
	var rowsLength = Object.keys(selectedrows).length;
	if(rowsLength > 0){
		for (var i in selectedrows) {
			var selrow = selectedrows[i];
			//循环当前列后面的所有列，设置所有单元格的值，（列号-1）
			for (var col = 1; col <= currentSheet.defaultcols; col++) {
				var cellkey = 'cell_' + selrow + '_' + col;
				var rowkey = 'row_'+selrow;
				delete currentSheet.row.cell[cellkey];
				delete currentSheet.row[rowkey];
			}
			for (var row = selrow + 1; row <= currentSheet.defaultrows; row++) {
				for (var col = 1; col <= currentSheet.defaultcols; col++) {
					var cellkey = 'cell_' + row + '_' + col;
					var rowkey = 'row_'+row;
					delete mergecells[cellkey];
					var cellObject = getCellObject(currentSheet,cellkey);
					var rowObject = getRowObject(currentSheet,rowkey);
					var cellObjectLen = Object.keys(cellObject).length;
					var rowObjectLen = Object.keys(rowObject).length;
					if(cellObjectLen > 0){
						//删除节点
						delete currentSheet.row.cell[cellkey];
						var changecellkey = 'cell_' + (row-1) + '_' + col;
						currentSheet.row.cell[changecellkey] = cellObject;
					}
					if(rowObjectLen > 0){
						//删除节点
						delete currentSheet.row[rowkey];
						var changerowkey = 'row_' + (row-1);
						currentSheet.row[changerowkey] = rowObject;
					}
				}
			}

			currentSheet.defaultrows = currentSheet.defaultrows - 1;
			
		}
		selectedrows = {};
		reloadWorkBook();
		
	}else{
		alert('选中移除的行');
	}
	
}
/**
* 移除列，选中列才可以进行操作
*/
function removeCol(){
	var colsLength = Object.keys(selectedcols).length;
	if(colsLength > 0){
		for (var i in selectedcols) {
			var selcol = selectedcols[i];
			
			//循环当前列后面的所有列，设置所有单元格的值，（列号-1）
			for (var row = 1; row <= currentSheet.defaultrows; row++) {
				var cellkey = 'cell_' + row + '_' + selcol;
				var colkey = 'col_'+selcol;
				delete currentSheet.row.cell[cellkey];
				delete currentSheet.column[colkey];
			}
			for (var col = selcol + 1; col <= currentSheet.defaultcols; col++) {
				//console.log(col);
				for (var row = 1; row <= currentSheet.defaultrows; row++) {
					var cellkey = 'cell_' + row + '_' + col;
					var colkey = 'col_'+col;
					delete mergecells[cellkey];
					var cellObject = getCellObject(currentSheet,cellkey);
					var colObject = getColObject(currentSheet,colkey);
					var cellObjectLen = Object.keys(cellObject).length;
					var colObjectLen = Object.keys(colObject).length;
					if(cellObjectLen > 0){
						//删除节点
						delete currentSheet.row.cell[cellkey];
						
						var changecellkey = 'cell_' + row + '_' + (col-1);
						currentSheet.row.cell[changecellkey] = cellObject;
					}
					if(colObjectLen > 0){
						//删除节点
						delete currentSheet.column[colkey];
						var changecolkey = 'col_' + (col-1);
						currentSheet.column[changecolkey] = colObject;
					}
					
				}
			}

			currentSheet.defaultcols = currentSheet.defaultcols - 1;
		}
		selectedcols = {};
		reloadWorkBook();
	}else{
		alert('选中移除的列');
	}
}

 
/**
* 上下移动行
*/
function moveRow(direction){
	var rowsLength = Object.keys(selectedrows).length;
	if(rowsLength > 0){
		for (var i in selectedrows) {
			var selrow = selectedrows[i];
			var rowkey = 'row_' + selrow;
			var selrowObject = getRowObject(currentSheet,rowkey);
			var rowcells = getRowCellsObject(currentSheet,selrow);
			//上移
			if('up' == direction && selrow > 1){
				//获取上一行对象及上一行所有单元格
				var uprow = selrow - 1;
				var uprowkey = 'row_' + uprow;
				var uprowObject = getRowObject(currentSheet,uprowkey);
				var uprowcells = getRowCellsObject(currentSheet,uprow);
				for (var col = 1; col <= currentSheet.defaultcols; col++) {
					//如果列单独设置，先使用列，否则默认即可
					var cellkey = 'cell_' + selrow + '_' + col;
					var upcellkey = 'cell_' + (selrow - 1) + '_' + col;
					delete currentSheet.row.cell[cellkey];
					delete currentSheet.row.cell[upcellkey];
					currentSheet.row.cell[cellkey] = uprowcells[upcellkey];
					currentSheet.row.cell[upcellkey] = rowcells[cellkey];
				}

				selectedrows = {};
				selectedrows[uprow] = uprow;

				reloadWorkBook();
			}
			//下移
			if('down' == direction && selrow < currentSheet.defaultrows){
				//获取上一行对象及上一行所有单元格
				var downrow = selrow + 1;
				var downrowkey = 'row_' + downrow;
				var downrowObject = getRowObject(currentSheet,downrowkey);
				var downrowcells = getRowCellsObject(currentSheet,downrow);

				for (var col = 1; col <= currentSheet.defaultcols; col++) {
					//如果列单独设置，先使用列，否则默认即可
					var cellkey = 'cell_' + selrow + '_' + col;
					var downcellkey = 'cell_' + (selrow + 1) + '_' + col;
					delete currentSheet.row.cell[cellkey];
					delete currentSheet.row.cell[downcellkey];
					currentSheet.row.cell[cellkey] = downrowcells[downcellkey];
					currentSheet.row.cell[downcellkey] = rowcells[cellkey];
				}

				selectedrows = {};
				selectedrows[downrow] = downrow;

				reloadWorkBook();
			}
		}
	}
}

/**
* 左右移动列
*/
function moveCol(direction){
	var colsLength = Object.keys(selectedcols).length;
	if(colsLength > 0){
		for (var i in selectedcols) {
			var selcol = selectedcols[i];
			var colkey = 'col_' + selcol;
			var selcolObject = getColObject(currentSheet,colkey);
			var colcells = getColCellsObject(currentSheet,selcol);
			//上移
			if('left' == direction && selcol > 1){
				//获取上一行对象及上一行所有单元格
				var leftcol = selcol - 1;
				var leftcolkey = 'col_' + leftcol;
				var leftcolObject = getColObject(currentSheet,leftcolkey);
				var leftcolcells = getColCellsObject(currentSheet,leftcol);
				for (var row = 1; row <= currentSheet.defaultrows; row++) {
					//如果列单独设置，先使用列，否则默认即可
					var cellkey = 'cell_' + row + '_' + selcol;
					var leftcellkey = 'cell_' + row + '_' + (selcol-1);
					delete currentSheet.row.cell[cellkey];
					delete currentSheet.row.cell[leftcellkey];
					currentSheet.row.cell[cellkey] = leftcolcells[leftcellkey];
					currentSheet.row.cell[leftcellkey] = colcells[cellkey];
				}

				selectedcols = {};
				selectedcols[leftcol] = leftcol;

				reloadWorkBook();
			}
			//下移
			if('right' == direction && selcol < currentSheet.defaultcols){
				//获取上一行对象及上一行所有单元格
				var rightcol = selcol + 1;
				var rightcolkey = 'col_' + rightcol;
				var rightcolObject = getColObject(currentSheet,rightcolkey);
				var rightcolcells = getColCellsObject(currentSheet,rightcol);

				for (var row = 1; row <= currentSheet.defaultrows; row++) {
					//如果列单独设置，先使用列，否则默认即可
					var cellkey = 'cell_' + row + '_' + selcol;
					var rightcellkey = 'cell_' + row + '_' + (selcol+1);
					delete currentSheet.row.cell[cellkey];
					delete currentSheet.row.cell[rightcellkey];
					currentSheet.row.cell[cellkey] = rightcolcells[rightcellkey];
					currentSheet.row.cell[rightcellkey] = colcells[cellkey];
				}

				selectedcols = {};
				selectedcols[rightcol] = rightcol;

				reloadWorkBook();
			}
		}
	}
}

/**
* 清除已选择的单元格
*/
function clearSelectedCells(){
	selectedcells = {};
	reloadWorkBook();
}
/**
* 合并单元格，选中的单元格进行合并操作
* 支持：多行合并、多列合并
* ？后续增加多行、多列合并？
*/
function mergeCells(){
	var bcolMerge = true;
	var browMerge = true;
	var mergerows = [];
	var mergecols = [];
	var fRow = null;
	var fCol = null;
	var mergin
	for (var i in selectedcells) {
		var cell = selectedcells[i];
		var row = cell.row;
		var col = cell.col;
		mergerows.push(row);
		mergecols.push(col);
		if(fRow == null && fCol == null){
			fRow = row;
			fCol = col;
		}
		if(fRow != row){
			bcolMerge = false;
		}
		if(fCol != col){
			browMerge = false;
		}
	}

	function compare(val1,val2){
		return val1-val2;
	};
	var mergeLength = Object.keys(selectedcells).length;
	if( mergeLength > 1 && (browMerge || bcolMerge)){
		var mergerows = mergerows.sort(compare);
		var mergecols = mergecols.sort(compare);
		var cellkey_first = 'cell_' + mergerows[0] + '_' + mergecols[0];
		if(browMerge){
			setCellAttr(currentSheet,cellkey_first,'mergeDown',mergeLength - 1);
		}else if(bcolMerge){
			setCellAttr(currentSheet,cellkey_first,'mergeAcross',mergeLength - 1);
		}
		
		selectedcells = {};
		reloadWorkBook();
	}else{
		alert('请选择同行或同列的2个以上单元格进行合并');
	}
}
/**
* 取消合并的单元格
*/
function cancelMergeCells(){
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength == 1){
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			removeCellAttr(currentSheet,cellkey,'mergeDown');
			removeCellAttr(currentSheet,cellkey,'mergeAcross');
			
		}
		mergecells = {};
		reloadWorkBook();
	}else{
		alert('请选择要取消的单元格');
	}

	
}
/**
* 保存工作簿信息
*/
function saveWorkbook(){
	console.log(JSON.stringify(workbook));
}

/**
* 根据数据，加载初始化工作簿
*/
function loadWorkbook(){
	workbook = JSON.parse(data1);
	//console.log(workbook);
	createWorkBook(workbook);
}

function changeSample(){
	mergecells = {};
	var sample = $('#sample option:selected').val();
	if(sample){
		if(sample == 'sample1'){
			workbook = JSON.parse(data);
			//console.log(workbook);
			createWorkBook(workbook);
		}
		if(sample == 'sample2'){
			workbook = JSON.parse(data1);
			//console.log(workbook);
			createWorkBook(workbook);
		}
		if(sample == 'sample3'){
			workbook = JSON.parse(data2);
			//console.log(workbook);
			createWorkBook(workbook);
		}
	}else{
		createWorkBook();
	}
}
/**
* 设置单元格字体样式
*/
function setCellFont(fontitem){
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength  > 0){
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			//console.log(fontFamily);
			if(fontitem == 'font-family'){
				var fontFamily = $('#selFontFamily option:selected').val();
				if(fontFamily){
					setCellAttr(currentSheet,cellkey,'font-family',fontFamily);
				}
			}
			if(fontitem == 'font-size'){
				var fontsize = $('#selFontSize option:selected').val();
				if(fontsize){
					setCellAttr(currentSheet,cellkey,'font-size',fontsize);
				}
			}
			if(fontitem == 'font-weight'){
				if(currentSheet.row && currentSheet.row.cell && currentSheet.row.cell[cellkey]&& currentSheet.row.cell[cellkey]['font-weight']){
					var fontweight = currentSheet.row.cell[cellkey]['font-weight'];
					fontweight = fontweight == 'normal'?'bold':'normal';
					setCellAttr(currentSheet,cellkey,'font-weight',fontweight);
				}else{
					setCellAttr(currentSheet,cellkey,'font-weight','bold');
				}
			}
			if(fontitem == 'font-style'){
				if(currentSheet.row && currentSheet.row.cell && currentSheet.row.cell[cellkey]&& currentSheet.row.cell[cellkey]['font-style']){
					fontstyle = currentSheet.row.cell[cellkey]['font-style'];
					fontstyle = fontstyle == 'normal'?'italic':'normal';
					setCellAttr(currentSheet,cellkey,'font-style',fontstyle);
				}else{
					setCellAttr(currentSheet,cellkey,'font-style','italic');
				}
			}
		}
	}

	reloadWorkBook();
}

function calculateCellTotal(){
	var total = 0;
	for (var i in selectedcells) {
		var cell = selectedcells[i];
		var row = cell.row;
		var col = cell.col;
		var cellkey = 'cell_' + row + '_' + col;
		var v = getCellData(currentSheet,cellkey);
		total += parseFloat(v);
	}
	alert(total);
	return total;
	
}

function calculateCellCount(){
	var num = 0;
	for (var i in selectedcells) {
		++num;
	}
	alert(num);
	return num;
	
}

function calculateCellAve(){
	var total = 0;
	var num = 0;
	for (var i in selectedcells) {
		var cell = selectedcells[i];
		var row = cell.row;
		var col = cell.col;
		var cellkey = 'cell_' + row + '_' + col;
		var v = getCellData(currentSheet,cellkey);
		total += parseFloat(v);
		++num;
	}
	
	alert(total/num);
	return total/num;
}

function calculateCellMax(){
	var max = 0;
	var num = 0;
	for (var i in selectedcells) {
		var cell = selectedcells[i];
		var row = cell.row;
		var col = cell.col;
		var cellkey = 'cell_' + row + '_' + col;
		var v = getCellData(currentSheet,cellkey);
		if(num == 0){
			max = parseFloat(v);
		}
		if(parseFloat(v) > max){
			max = parseFloat(v);
		}
		num++;
	}
	
	alert(max);
	return max;
}

function calculateCellMin(){
	var min = 0;
	var num = 0;
	for (var i in selectedcells) {
		var cell = selectedcells[i];
		var row = cell.row;
		var col = cell.col;
		var cellkey = 'cell_' + row + '_' + col;
		var v = getCellData(currentSheet,cellkey);
		if(num == 0){
			min = parseFloat(v);
		}
		if(parseFloat(v) < min){
			min = parseFloat(v);
		}
		num++;
	}
	
	alert(min);
	return min;
}

function setCellAlign(alignname){
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength > 0){
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			setCellAttr(currentSheet,cellkey,'text-align',alignname);
		}
	}

	reloadWorkBook();
}

function changeCellDatatype(){
	
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength == 1){
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			var datatype = $('#celldatatype option:selected').val();
			setCellDataType(currentSheet,cellkey,datatype);
		}
	}

	reloadWorkBook();
}

function setCellVAlign(alignname){
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength  > 0){
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			setCellAttr(currentSheet,cellkey,'text-valign',alignname);
		}
	}

	reloadWorkBook();
}

function colSort(type){
	function compareASC(val1,val2){
		return val1-val2;
	};

	function compareDESC(val1,val2){
		return val2-val1;
	};

	
	var colsLength = Object.keys(selectedcols).length;
	if(colsLength > 0){
		for (var i in selectedcols) {
			var selcol = selectedcols[i];
			var colvalues = [];
			//循环列，获取值，进行排序处理
			for (var row = 1; row <= currentSheet.defaultrows; row++) {
				var cellkey = 'cell_' + row + '_' + selcol;
				var celldata = getCellData(currentSheet,cellkey);
				colvalues.push(celldata);
			}
			if('asc' == type){
				var colvalues = colvalues.sort(compareASC);
			}else if('desc' == type){
				var colvalues = colvalues.sort(compareDESC);
			}

			for (var row = 1; row <= currentSheet.defaultrows; row++) {
				var cellkey = 'cell_' + row + '_' + selcol;
				var celldata = colvalues[row - 1];
				setCellData(currentSheet,cellkey,celldata);
			}
			//console.log(colvalues);
			reloadWorkBook();
			//selectedcols = {};
		}
	}else{
		alert('选中要排序的列');
	}
	
}

var tempCopyOrCutCell = [];

function copycells(){
	tempCopyOrCutCell = [];
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength  > 0){
		$("#copybtn").addClass('active');
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			var cellObject = getCellObject(currentSheet,cellkey);
			tempCopyOrCutCell.push(cellObject);
		}
	}else{
		alert('选中复制的单元格');
	}
}

function cutcells(){
	tempCopyOrCutCell = [];
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength  > 0){
		$("#cutbtn").addClass('active');
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			var cellObject = getCellObject(currentSheet,cellkey);
			tempCopyOrCutCell.push(cellObject);
			delete currentSheet.row.cell[cellkey];
		}
		reloadWorkBook();
	}else{
		alert('选中剪切的单元格');
	}
}
function pastecells(){
	if(tempCopyOrCutCell.length > 0){
		$("#copybtn").removeClass('active');
		$("#cutbtn").removeClass('active');
		var selCellsLength = Object.keys(selectedcells).length;
		for(var i in tempCopyOrCutCell){
			var tempCell = tempCopyOrCutCell[i];
			console.log(tempCell);
		}
		//console.log(tempCopyOrCutCell.length);
		if(selCellsLength  > 0 && tempCopyOrCutCell.length == selCellsLength){
			var no = 0;
			for (var i in selectedcells) {
				var cell = selectedcells[i];
				var row = cell.row;
				var col = cell.col;
				var cellkey = 'cell_' + row + '_' + col;
				var tempCell = tempCopyOrCutCell[no];
				currentSheet.row.cell[cellkey] = tempCell;
				no++;
			}
			reloadWorkBook();
		}else{
			alert('选中粘贴的单元格');
		}
	}else{
		alert('请先选中复制或剪切单元格');
	}
	
}

function getRandom(min, max){
	var r = Math.random() * (max - min);
	var re = Math.round(r + min);
	re = Math.max(Math.min(re, max), min)
	 
	return re;
}

function createChart(chartype){
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength > 0){
		$('#myModal').modal();
		var xAxis = [];
		var series_data = [];
		// 循环行
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			var cellkey = 'cell_' + row + '_' + col;
			var cellvalue = getCellData(currentSheet,cellkey);
			xAxis.push(row + '_' + col);
			series_data.push(cellvalue);
		}
		
		// 基于准备好的dom，初始化echarts实例
		var myChart = echarts.init(document.getElementById('echartsmain'));

		// 指定图表的配置项和数据
		var option = {
			title: {
				text: '统计图'
			},
			tooltip: {},
			legend: {
				data:['数值']
			},
			xAxis: {
				data: xAxis
			},
			yAxis: {},
			series: [{
				name: '数值',
				type: chartype?chartype:'bar',
				data: series_data
			}]
		};

		if(chartype == 'pie'){
			delete option.xAxis;
			delete option.yAxis;
		}

		// 使用刚指定的配置项和数据显示图表。
		myChart.setOption(option);
	}else{
		alert('请先选中统计的单元格');
	}
}

function insertImage(){
	var selCellsLength = Object.keys(selectedcells).length;
	if(selCellsLength > 0){
		var cellkey = '';
		// 循环行
		for (var i in selectedcells) {
			var cell = selectedcells[i];
			var row = cell.row;
			var col = cell.col;
			cellkey = 'cell_' + row + '_' + col;
		}
		$('#imagemodal').modal();

		$("#image_file").change(function () {
			var $file = $(this);
			var fileObj = $file[0];
			var windowURL = window.URL || window.webkitURL;
			var dataURL;
			var $img = $("#selimage");

			if (fileObj && fileObj.files && fileObj.files[0]) {
				//dataURL = windowURL.createObjectURL(fileObj.files[0]);
				//$img.attr('src', dataURL);
				var reader = new FileReader();
				reader.readAsDataURL(fileObj.files[0]);
				reader.onload =function(e){
					$img.attr('src',this.result);
					setCellData(currentSheet,cellkey,this.result);
					reloadWorkBook();
				}
				
			}
			/*else {
				dataURL = $file.val();
				setCellData(currentSheet,cellkey,dataURL);
				var imgObj = document.getElementById("selimage");
				// 两个坑:
				// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
				// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
				imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
				imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

			}
			*/
		});
		
	}else{
		alert('请先选中统计的单元格');
	}
}